package com.x.compute.common.function;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDecimal;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 四舍五入函数
 * 函数示例：ROUND(arg1, arg2)
 * arg1-小数，arg2-保留小数位数
 *
 * @author xuxin
 */
public class RoundFunction extends AbstractFunction {

    @Override
    public String getName() {
        return "ROUND";
    }

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        Number left = FunctionUtils.getNumberValue(arg1, env);
        Number right = FunctionUtils.getNumberValue(arg2, env);
        BigDecimal value = new BigDecimal(left.toString()).setScale(right.intValue(), BigDecimal.ROUND_HALF_UP);
        return new AviatorDecimal(value);
    }

}
